﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Trade.Library.Data
{
    /// <summary>
    /// 
    /// </summary>
    public class CommonMap
    {
        /// <summary>
        /// 将IDataReader映射为泛型T的集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static IEnumerable<T> MapToIEnumerable<T>(IDataReader dr)
        {
            using (dr)
            {
                List<string> field = new List<string>(dr.FieldCount);
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    field.Add(dr.GetName(i).ToLower());
                }
                while (dr.Read())
                {
                    T model = Activator.CreateInstance<T>();
                    foreach (PropertyInfo property in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (field.Contains(property.Name.ToLower()))
                        {
                            if (property.PropertyType.IsEnum) //属性类型是否表示枚举
                            {
                                object enumName = Enum.ToObject(property.PropertyType, property.GetValue(model, null));
                                property.SetValue(model, enumName, null); //获取枚举值，设置属性值
                            }
                            else
                            {
                                if (!IsNullOrDBNull(dr[property.Name]))
                                {
                                    property.SetValue(model, HackType(dr[property.Name], property.PropertyType), null);
                                }
                            }
                        }
                    }
                    yield return model;
                }
            }

        }

        /// <summary>
        /// 将IDataReader映射为泛型T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T MapToModel<T>(IDataReader dr)
        {
            using (dr)
            {
                if (dr.Read())
                {
                    List<string> list = new List<string>(dr.FieldCount);
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        list.Add(dr.GetName(i).ToLower());
                    }
                    T model = Activator.CreateInstance<T>();
                    foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (list.Contains(pi.Name.ToLower()))
                        {
                            if (pi.PropertyType.IsEnum) //属性类型是否表示枚举
                            {
                                object enumName = Enum.ToObject(pi.PropertyType, pi.GetValue(model, null));
                                pi.SetValue(model, enumName, null); //获取枚举值，设置属性值
                            }
                            else
                            {
                                if (!IsNullOrDBNull(dr[pi.Name]))
                                {
                                    pi.SetValue(model, HackType(dr[pi.Name], pi.PropertyType), null);
                                }
                            }
                        }
                    }
                    return model;
                }
            }
            return default(T);
        }

        /// <summary>
        /// 将DataRow映射为泛型T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T MapToModel<T>(DataRow dr)
        {
            try
            {
                List<string> list = new List<string>(dr.ItemArray.Length);
                for (int i = 0; i < dr.ItemArray.Length; i++)
                {
                    list.Add(dr.Table.Columns[i].ColumnName.ToLower());
                }
                T model = Activator.CreateInstance<T>();
                foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                {
                    if (list.Contains(pi.Name.ToLower()))
                    {
                        if (pi.PropertyType.IsEnum) //属性类型是否表示枚举
                        {
                            object enumName = Enum.ToObject(pi.PropertyType, pi.GetValue(model, null));
                            pi.SetValue(model, enumName, null); //获取枚举值，设置属性值
                        }
                        else
                        {
                            if (!IsNullOrDBNull(dr[pi.Name]))
                            {
                                pi.SetValue(model, HackType(dr[pi.Name], pi.PropertyType), null);
                            }
                        }
                    }
                }
                return model;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 将DataTable映射为泛型T的集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static IEnumerable<T> MapToIEnumerable<T>(DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                yield return MapToModel<T>(dt.Rows[i]);
            }
        }

        /// <summary>
        /// 判断可空类型
        /// </summary>
        /// <param name="value"></param>
        /// <param name="conversionType"></param>
        /// <returns></returns>
        public static object HackType(object value, Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (IsNullOrDBNull(value))
                    return null;
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }
            if (conversionType == typeof(bool) || conversionType == typeof(Boolean))
            {
                if (value is string)
                {
                    if (value.ToString() == "1")
                        return true;
                    else
                        return false;
                }
            }
            if (conversionType.IsEnum) //属性类型是否表示枚举
            {
                int intvalue;
                if (int.TryParse(value.ToString(), out intvalue))
                    return Enum.ToObject(conversionType, Convert.ToInt32(value));
                else
                    return System.Enum.Parse(conversionType, value.ToString(), false);
            }
            return Convert.ChangeType(value, conversionType);
        }

        /// <summary>
        /// 将object类型转换为指定的类型T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T ChangeType<T>(object value)
        {
            Type t = typeof(T);
            if (CommonMap.IsNullOrDBNull(value))
                value = t.IsValueType ? Activator.CreateInstance(t) : null;
            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                try
                {
                   // return (T)value;
                    return (T)Convert.ChangeType(value, t.GetGenericArguments()[0]);

                }
                catch
                {
                    value = null;
                    return (T)value;
                }
            }
            return (T)Convert.ChangeType(value, typeof(T));
        }

        /// <summary>
        /// 判断null或DBNull
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsNullOrDBNull(object obj)
        {
            return ((obj is DBNull) || obj == null || string.IsNullOrEmpty(obj.ToString())) ? true : false;
        }

        /// <summary>
        /// 根据IList获取DataTable
        /// </summary>
        /// <typeparam name="T">泛型类型</typeparam>
        /// <param name="list">泛型列表</param>
        /// <returns>数据类型</returns>
        public static DataTable GetDataTableFromIList<T>(IList<T> list)
        {
            DataTable dt = new DataTable();
            dt.TableName = "t";
            Type type = typeof(T);
            var properties = type.GetProperties();
            foreach (var item in properties)
            {
                dt.Columns.Add(item.Name);
            }
            foreach (var item in list)
            {
                object[] data = new object[properties.Length];
                for (int i = 0; i < properties.Length; i++)
                {
                    data[i] = properties[i].GetValue(item, null);
                }
                dt.Rows.Add(data);
            }
            return dt;
        }

    }
}
